﻿package component.formula.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

class Node {
	private String id; // 节点ID

	private String name; // 节点名称

	private String parentId; // 父节点ID
	
	private Map nodeMap;

	private List childNodes; // 子节点集合

	public void addChild(Node node) {
		if (childNodes == null) {
			childNodes = new ArrayList();
		}
		childNodes.add(node);
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public Map getNodeMap() {
		return nodeMap;
	}

	public void setNodeMap(Map nodeMap) {
		this.nodeMap = nodeMap;
	}

}

public class TreeBuilder {

	public TreeBuilder(List treeList) {
		this.treeList = treeList;
	}

	private String idName = "id";
	private String parentIdName = "parentId";
	private String orderName = "order";
	private String rootId = "0";

	private List treeList;

	public void build() {
		// 首先把需要记录取出来放到一个Map集合里。
		Map map = new HashMap();

		Node node = null;
		for (int i = 0; i < treeList.size(); i++) {
			Map rowMap = (Map) treeList.get(i);

			// 创建节点对象
			node = new Node();
			node.setId((String) rowMap.get(this.idName));
			node.setParentId((String)rowMap.get(this.parentIdName));
			node.setNodeMap(rowMap);

			// 创建好就添加到集合里
			map.put(node.getId(), node);
		}

		// 获取到所有数据后需要遍历一次map
		Collection c = map.values();
		Iterator iter = c.iterator();
		while (iter.hasNext()) {
			Node currentNode = (Node) iter.next();

			// 用当前对象的父节点ID在map中找出父节点对象
			Node parentNode = (Node) map.get(currentNode.getParentId());
			if (parentNode != null) {
				// 为父节点对象添加子节点
				parentNode.addChild(currentNode);
			}
		}
	}

	public String getIdName() {
		return idName;
	}

	public void setIdName(String idName) {
		this.idName = idName;
	}

	public String getParentIdName() {
		return parentIdName;
	}

	public void setParentIdName(String parentIdName) {
		this.parentIdName = parentIdName;
	}

	public String getOrderName() {
		return orderName;
	}

	public void setOrderName(String orderName) {
		this.orderName = orderName;
	}

	public String getRootId() {
		return rootId;
	}

	public void setRootId(String rootId) {
		this.rootId = rootId;
	}
	
	

}
